package hong.jun.server;

import hong.jun.doamin.MyUser;
import hong.jun.doamin.Permission;
import hong.jun.mapper.MyUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Component
/**覆写UserDetailsService的方法 将从数据库得到的user封装给UserDetail*/
// 然后进行AuthenticationManager委托AuthenticationProvider(DaoAuthenticationProvider)进行认证
// AuthenticationProvider通过调用UserDetailsService获取到数据库中存储的用户信息(UserDetails)，
// 然后调用passwordEncoder密码编码器对UsernamePasswordAuthenticationToken中的密码和UserDetails中的密码进行比较
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private MyUserMapper myUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUseruser = myUserMapper.selectbyusername(username);
        if (myUseruser == null) {
            throw new UsernameNotFoundException("无此用户");
        }
        //System.out.println("----------------"+myUseruser);
        List<GrantedAuthority> authorities = new ArrayList<>();//模拟权限数组
        List<Permission> permissions1 = myUseruser.getPermissions();
        permissions1.forEach(permission -> {
            authorities.add(new SimpleGrantedAuthority(permission.getName()));
        });
        String passeord = myUseruser.getPassword();
        return new User(username, passeord, authorities);
    }
}
